package system

import (
	"a-admin/web/resp"
	"a-common/constant"
	"a-common/core/redis"
	"a-common/myerr"
	"a-system/domain/pojo"
	"a-system/service"
	"fmt"
	"strings"
	"sync"

	"github.com/gofiber/fiber/v2"
)

var (
	logininforControllerTemp *LogininforController
	sysLogininforService     = service.NewSysLogininforService()
	logininforControllerOnce sync.Once
)

type LogininforController struct{}

func NewSysLogininforController() *LogininforController {
	logininforControllerOnce.Do(func() {
		logininforControllerTemp = &LogininforController{}
	})
	return logininforControllerTemp
}

// List 分页
func (m *LogininforController) List(c *fiber.Ctx) error {
	var args pojo.SysLogininforDto
	if err := c.QueryParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	err := args.Validator()
	if err != nil {
		return myerr.ERR_SYS_ARGS
	}

	pageVo, err := sysLogininforService.List(&args)
	if err != nil {
		return err
	}
	return resp.Resp(c, pageVo)
}

// Export 导出
func (m *LogininforController) Export(c *fiber.Ctx) error {
	var args pojo.SysLogininforDto
	if err := c.QueryParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	f, err := sysLogininforService.Export(&args)
	if err != nil {
		return myerr.ERR_FILE_WRITE
	}
	c.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, "登陆日志表.xlsx"))
	if err := f.Write(c.Response().BodyWriter()); err != nil {
		return myerr.ERR_FILE_WRITE
	}
	return nil
}

// Clear 清空
func (m *LogininforController) Clear(c *fiber.Ctx) error {
	return resp.Ok(c)
}

// Quit 强退
func (m *LogininforController) Quit(c *fiber.Ctx) error {
	tokens := c.Params("tokens")
	if tokens == "" {
		return myerr.ERR_SYS_ARGS
	}
	token := strings.Split(tokens, ",")
	for idx, item := range token {
		token[idx] = constant.LOGIN_SESSION + item
	}
	if err := redis.New().Del(token...); err != nil {
		return err
	}
	return resp.Ok(c)
}

// Unlock 解锁
func (m *LogininforController) Unlock(c *fiber.Ctx) error {
	userNames := c.Params("names")
	if userNames == "" {
		return myerr.ERR_SYS_ARGS
	}
	names := strings.Split(userNames, ",")
	for idx, item := range names {
		names[idx] = constant.PWD_ERR_CNT_KEY + item
	}
	if err := redis.New().Del(names...); err != nil {
		return err
	}
	return resp.Ok(c)
}
